package net.xt.testthread.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@Slf4j
@EnableAsync
public class MyThreadPoolConfig {

    /**
     * 自定义spring中的线程池ThreadPoolTaskExecutor
     *
     * @return
     */
    @Bean
    public ThreadPoolTaskExecutor getMyThreadPool() {
        ThreadPoolTaskExecutor myThreadPool = new ThreadPoolTaskExecutor();
        myThreadPool.setThreadNamePrefix("myThreadPool-");  // 设置自定义名称的前缀
        myThreadPool.setCorePoolSize(Runtime.getRuntime().availableProcessors() * 2 + 1);    // 如果任务是io密集型，网络请求比较多，设置为CPU核数*2+1
        myThreadPool.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 4 + 1);     // 最大值设置为CPU核数*4+1
        myThreadPool.setQueueCapacity(100);     // 队列容量
        myThreadPool.setKeepAliveSeconds(60);   // 线程存活时间，单位：秒
        // 设置拒绝策略
        myThreadPool.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor executor) -> {
            log.info("当前任务线程池队列已满!");
        });
        // 设置线程池中的异常处理方式
        myThreadPool.setThreadFactory(runnable -> {
            Thread newThread = myThreadPool.newThread(runnable);

            // 自定义处理线程池中的异常
            newThread.setUncaughtExceptionHandler((thread, throwable) -> {
                log.error("thread--> {},throwable--> {}", thread.getName(), throwable.getMessage());
            });
            return newThread;
        });
        // 线程池初始化
        myThreadPool.initialize();

        return myThreadPool;
    }

}
